<template>
  <div class="app-container">
    <!-- 顶部控制台 -->
    <div class="filter-container">
      <div class="container-layout-left">
        <el-input class="filter-item" style="width: 200px; margin-left: 0px" size="mini" placeholder="标题" v-model="form.searchTitle"/>
        <el-input class="filter-item" style="width: 200px; margin-left: 0px" size="mini" placeholder="作者" v-model="form.searchAuthor"/>
        <el-select class="filter-item" style="width: 120px" size="mini" v-model="form.searchType" @change="handlePageInit">
          <el-option v-for="item in pageData.searchTypeList" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
        <el-select class="filter-item" style="width: 120px" size="mini" v-model="form.searchStatus" @change="handlePageInit">
          <el-option v-for="item in pageData.searchStatusList" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
        <el-button type="primary" size="mini" icon="el-icon-search" @click="handlePageInit">搜索</el-button>
        <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleOpenSavePage">添加</el-button>
      </div>
    </div>
    <!-- 页面数据列表 -->
    <el-table :data="responseData.tableList"
              border style="width: 100%;"
              v-loading="pageData.loading"
              element-loading-text="拼命加载中"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(0, 0, 0, 0.8)"
              :header-cell-style="{ background: '#545C64', color: '#ffffff' }"
              @selection-change="handleTableSelection">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column fixed="left" prop="id" label="数据ID" width="100" align="center"/>
      <el-table-column prop="type" label="类型" width="120" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.type === 1"><el-tag type="primary">新书推荐</el-tag></span>
          <span v-if="scope.row.type === 2"><el-tag type="success">精品好书</el-tag></span>
          <span v-if="scope.row.type === 3"><el-tag type="warning">每日一听</el-tag></span>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" width="260" align="center"/>
      <el-table-column prop="info" label="说明" width="260" align="center"/>
      <el-table-column prop="author" label="作者" width="120" align="center"/>
      <el-table-column prop="job" label="职位" width="80" align="center"/>
      <el-table-column prop="image" label="展示图" width="120" align="center">
        <template slot-scope="scope">
              <span v-if="scope.row.image != null && scope.row.image !== ''">
                <el-button size="small" width="120" type="success" @click="handleCheckInfo(scope)">预览</el-button>
              </span>
          <span v-else >无</span>
        </template>
      </el-table-column>
      <el-table-column prop="showCount" label="展示数量" width="100" align="center"/>
      <el-table-column prop="showPrice" label="展示价格" width="100" align="center"/>
      <el-table-column prop="jumpUrl" label="跳转链接" width="240" align="center"/>
      <el-table-column prop="status" label="可用状态" width="120" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 0"><el-tag type="success">下架</el-tag></span>
          <span v-if="scope.row.status === 1"><el-tag type="warning">发布</el-tag></span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160" align="center"/>
      <el-table-column prop="updateTime" label="更新时间" width="160" align="center"/>
      <el-table-column fixed="right" label="操作" width="300" align="center">
        <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleOpenEditPage(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.status === 0" size="mini" type="success" @click="handleUpdateDataStatus(scope, 1)">发布</el-button>
            <el-button v-if="scope.row.status === 1" size="mini" type="warning" @click="handleUpdateDataStatus(scope, 0)">下架</el-button>
            <el-button size="mini" type="danger" @click="handleDeleteData(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页器-->
    <el-pagination
      layout="total, sizes, prev, pager, next, jumper"
      :current-page="form.pageNum"
      :page-size="form.pageSize"
      :total="form.total"
      :page-sizes="[12, 50, 100, 200]"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange">
    </el-pagination>
    <!--图片预览隐藏域-->
    <el-dialog title="图片预览" :visible.sync="pageData.checkPanelStatus" size="tiny" width="480px">
      <el-card :body-style="{ padding: '0px' }">
        <div>
          <div>
            <img :src="pageData.checkPanelInfo" width="450px" height="450px">
          </div>
        </div>
      </el-card>
    </el-dialog>
    <!-- 新增/修改隐藏域 -->
    <el-dialog :title="pageData.savePanelTitle" :visible.sync="pageData.savePanelStatus" size="tiny"
               :before-close="handleCloseSavePage">
      <el-form ref="form" :model="form" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-row>
              <el-col>
                <el-form-item label="标题">
                  <el-input v-model="form.title" maxlength="16" show-word-limit></el-input>
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="说明">
                  <el-input type="textarea" v-model="form.info" :rows="5" maxlength="40" show-word-limit></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图片">
              <el-upload
                class="avatar-uploader"
                action="/api/cms/common/uploadFile"
                :show-file-list="false"
                :on-success="handleImageUploadSuccess">
                <img v-if="form.image" :src="form.image" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" style="line-height: 178px"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="作者">
              <el-input v-model="form.author" maxlength="15" show-word-limit></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职务">
              <el-input v-model="form.job" maxlength="15" show-word-limit></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分类">
              <el-select v-model="form.type" placeholder="请选择所属分类">
                <el-option label="新书推荐" :value="1"></el-option>
                <el-option label="精品好书" :value="2"></el-option>
                <el-option label="每日一听" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio :label="0" >下架</el-radio>
                <el-radio :label="1" >发布</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="数量">
              <el-input v-model="form.showCount" maxlength="10" show-word-limit></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格">
              <el-input v-model="form.showPrice" maxlength="10" show-word-limit></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="跳转地址">
              <el-input v-model="form.jumpUrl" maxlength="255" show-word-limit></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="handleSaveButtonClick">保存</el-button>
          <el-button @click="handleCloseSavePage">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  // 组件引入
  // 方法工具引入
  import { PermissionsToDetectFormUser } from '@/utils/PermissionsDetect';
  import { getPermission } from '@/utils/UserCookies';
  // 接口引入
  import { loadCmsDiscoveryList,saveCmsDiscoveryData,updateCmsDiscoveryData,batchReleaseCmsDiscoveryData,deleteCmsDiscoveryData } from "@/api/config";
  export default {
    name: "discovery",
    //import引入的组件需要注入到对象中才能使用
    components: {},
    data() {
      return {
        pageData:{
          searchTypeList: [
            {label: "不限", value: -1},
            {label: "新书推荐", value: 1},
            {label: "精品好书", value: 2},
            {label: "每日一听", value: 3},
          ],
          searchStatusList: [
            {label: "发布状态", value: -1},
            {label: "下架", value: 0},
            {label: "发布", value: 1},
          ],
          loading: false,
          // 图像预览
          checkPanelStatus: false,
          checkPanelInfo: "",
          // 新增/修改面板
          savePanelStatus: false,
          savePanelTitle: "",
          savePanelType: 1,
        },// 页面配置数据
        form:{
          searchTitle: "",
          searchAuthor: "",
          searchType: -1,
          searchStatus: -1,
          selection: [],
          pageNum: 1,
          pageSize: 12,
          total: 0,

          id: 0,
          title: "",
          author: "",
          type: 1,
          status: 0,
          info: "",
          job: "",
          image: "",
          showCount: 0,
          showPrice: 0,
          jumpUrl: ""
        },// 页面表单
        formRules: {},// 表单验证
        responseData: {
          tableList: []
        },// 接口响应数据
      }
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods:{
      handlePageInit(){
        this.form.pageNum = 1;
        this.pageData.loading = true;// 创建加载窗口
        this.loadCmsDiscoveryList();// 读取路由角色列表
      },// 页面初始化事件
      handleCurrentChange(val){
        this.form.pageNum = val;// 更换页码
        this.pageData.loading = true;// 创建加载窗口
        this.loadCmsDiscoveryList();// 读取路由角色列表
      },// 页码切换事件
      handleSizeChange(val){
        this.form.pageSize = val;// 更换页面大小
        this.pageData.loading = true;// 创建加载窗口
        this.loadCmsDiscoveryList();// 读取路由角色列表
      },// 页面size切换事件
      handleTableSelection(val){
        let list = [];// 初始化多选数组
        for (let i=0; i<val.length; i++){
          list.push(val[i].id);
        }// 遍历多选的列表，将ID拼入数组中
        this.form.selection = list;// 进行多选值的切换
      },// 表格多选事件
      handleCheckInfo(scope){
        this.pageData.checkPanelStatus = true;
        this.pageData.checkPanelInfo = scope.row.image;
      },// 预览图像(查看表格详情)
      handleOpenSavePage(){
        if (PermissionsToDetectFormUser(getPermission(), "720001")){
          // 初始化表单
          this.form.id = 0;
          this.form.title = "";
          this.form.author = "";
          this.form.type = 1;
          this.form.status = 0;
          this.form.info = "";
          this.form.job = "";
          this.form.image = "";
          this.form.showCount = 0;
          this.form.showPrice = 0;
          this.form.jumpUrl = "";
          // 打开面板
          this.pageData.savePanelStatus = true;
          this.pageData.savePanelTitle = "新的发现";
          this.pageData.savePanelType = 1;
        }  else {
          this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
        }
      },// 打开新增页
      handleOpenEditPage(scope){
        if (PermissionsToDetectFormUser(getPermission(), "720003")){
          // 初始化表单
          this.form.id = scope.id;
          this.form.title = scope.title;
          this.form.author = scope.author;
          this.form.type = scope.type;
          this.form.status = scope.status;
          this.form.info = scope.info;
          this.form.job = scope.job;
          this.form.image = scope.image;
          this.form.showCount = scope.showCount;
          this.form.showPrice = scope.showPrice;
          this.form.jumpUrl = scope.jumpUrl;
          // 打开面板
          this.pageData.savePanelStatus = true;
          this.pageData.savePanelTitle = "调整发现";
          this.pageData.savePanelType = 2;
        }  else {
          this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
        }
      },// 打开修改页
      handleCloseSavePage(){
        this.$confirm('确认关闭？').then(response => {
          // 初始化表单
          this.form.id = 0;
          this.form.title = "";
          this.form.author = "";
          this.form.type = 1;
          this.form.status = 0;
          this.form.info = "";
          this.form.job = "";
          this.form.image = "";
          this.form.showCount = 0;
          this.form.showPrice = 0;
          this.form.jumpUrl = "";
          // 打开面板
          this.pageData.savePanelStatus = false;
          this.pageData.savePanelTitle = "";
          this.pageData.savePanelType = 0;
        }).catch(err => {
          console.log(err);
        });
      },
      handleImageUploadSuccess(response){
        this.form.image = response.data;
      },// 图片上传成功
      handleSaveButtonClick(){
        if (this.pageData.savePanelType === 1){// 新增数据
          if (!PermissionsToDetectFormUser(getPermission(), "720001")){
            this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
          }
        } else if (this.pageData.savePanelType === 2){// 修改数据
          if (!PermissionsToDetectFormUser(getPermission(), "720003")){
            this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
          }
        }
        this.$confirm('是否保存当前数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.pageData.savePanelType === 1){// 新增数据
            this.saveCmsDiscoveryData();
          } else if (this.pageData.savePanelType === 2){// 修改数据
            this.updateCmsDiscoveryData();
          }
        }).catch(cancel => {
          console.log(cancel);
          this.$message.info("已取消操作");
        });
      },// 保存按钮点击事件
      handleUpdateDataStatus(scope){
        if (PermissionsToDetectFormUser(getPermission(), "720005")){
          this.$confirm("是否更改当前所选数据的发布状态?", "提示", {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let param = {
              id: scope.row.id,
              status: status
            };
            this.batchReleaseCmsDiscoveryData(param);
          }).catch(close => {
            console.log(close);
            this.$message.info("已取消操作");
          });
        } else {
          this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
        }
      },// 修改内容的发布状态
      handleDeleteData(scope){
        if (scope.row.status === 1){
          this.$message.warning('已发布数据无法直接删除，请先下架');
          return;
        }
        if (PermissionsToDetectFormUser(getPermission(), "720002")){
          this.$confirm('当前操作会删除所选数据的发布状态, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            // 拼接访问参数
            let prams = {id: scope.row.id};
            // 接口访问
            this.deleteCmsDiscoveryData(prams);
          }).catch(cancel => {
            console.log(cancel);
            this.$message.info("已取消操作");
          });
        }  else {
          this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
        }
      },// 删除按钮点击事件
      // 接口
      loadCmsDiscoveryList(){
        loadCmsDiscoveryList(this.form).then(response => {
          if (response.code === "200"){
            this.pageData.loading = false;
            this.responseData.tableList = response.data.list;
            this.form.total = response.data.total;
          } else {
            this.$message.warning(response.message);
          }
        }).catch( error =>{
          console.log(error);
          this.$message.error(error);
        })
      },// 获取发现数据
      saveCmsDiscoveryData(){
        saveCmsDiscoveryData(this.form).then(response => {
          if (response.code === "200"){
            this.$message.success("保存成功");
            // 初始化表单
            this.form.id = 0;
            this.form.title = "";
            this.form.author = "";
            this.form.type = 1;
            this.form.status = 0;
            this.form.info = "";
            this.form.job = "";
            this.form.image = "";
            this.form.showCount = 0;
            this.form.showPrice = 0;
            this.form.jumpUrl = "";
            // 打开面板
            this.pageData.savePanelStatus = false;
            this.pageData.savePanelTitle = "";
            this.pageData.savePanelType = 0;
            // 初始化数据
            this.handlePageInit();
          } else {
            this.$message.warning(response.message);
          }
        }).catch( error =>{
          console.log(error);
          this.$message.error(error);
        })
      },// 保存发现数据
      updateCmsDiscoveryData(){
        updateCmsDiscoveryData(this.form).then(response => {
          if (response.code === "200"){
            this.$message.success("保存成功");
            // 初始化表单
            this.form.id = 0;
            this.form.title = "";
            this.form.author = "";
            this.form.type = 1;
            this.form.status = 0;
            this.form.info = "";
            this.form.job = "";
            this.form.image = "";
            this.form.showCount = 0;
            this.form.showPrice = 0;
            this.form.jumpUrl = "";
            // 打开面板
            this.pageData.savePanelStatus = false;
            this.pageData.savePanelTitle = "";
            this.pageData.savePanelType = 0;
            // 初始化数据
            this.handlePageInit();
          } else {
            this.$message.warning(response.message);
          }
        }).catch( error =>{
          console.log(error);
          this.$message.error(error);
        })
      },// 更新发现数据
      batchReleaseCmsDiscoveryData(){
        batchReleaseCmsDiscoveryData(this.form).then(response => {
          if (response.code === "200"){
            this.$message.success('数据状态更新成功');
            this.handlePageInit();
          } else {
            this.$message.warning(response.message);
          }
        }).catch( error =>{
          console.log(error);
          this.$message.error(error);
        })
      },// 更新发现数据的发布状态
      deleteCmsDiscoveryData(prams){
        deleteCmsDiscoveryData(prams).then(response => {
          if (response.code === "200"){
            this.$message.success('数据状态更新成功');
            this.handlePageInit();
          } else {
            this.$message.warning(response.message);
          }
        }).catch( error =>{
          console.log(error);
          this.$message.error(error);
        })
      },// 删除数据接口
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created: function () {
      let _this = this;
      document.onkeydown = function(e) {
        if (!_this.pageData.loading) {
          let key = window.event.keyCode;
          if (key === 13) {
            _this.handlePageInit(); //此方法是当按下enter键后要做的动作。
          }
        }
      };
      setTimeout(function () {
        _this.handlePageInit();
      }, 800);
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {},
    beforeCreate() {}, //生命周期 - 创建之前
    beforeMount() {}, //生命周期 - 挂载之前
    beforeUpdate() {}, //生命周期 - 更新之前
    updated() {}, //生命周期 - 更新之后
    beforeDestroy() {}, //生命周期 - 销毁之前
    destroyed() {}, //生命周期 - 销毁完成
    activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
  };
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
</style>
